#include "mariogame.h"
#include "Engine2D/dxsurface.h"
#include "staticobject.h"
#include "dynamicobject.h"
#include "coin.h"
#include "mushroom.h"
#include "turtle.h"
#include "enemy.h"
#include <fstream>

using namespace std;

MarioGame::MarioGame(HINSTANCE hInst, const char* nameWnd) : DXGame(hInst, nameWnd, SCREEN_WIDTH, SCREEN_HEIGHT, 80)
{	
    background = 0;
    widthMap = 36 * 100;
    quadtree = new QuadTree<GameObject>(widthMap, SCREEN_HEIGHT, 8);
}

bool MarioGame::LoadContent()
{	
    background = new DXSurface("Data\\Mario Sprites\\Sky.png");
    factoryObj.CreateObject(1, 0, 0, 3);
    factoryObj.CreateObject(2, 20, 0, 2);
    factoryObj.CreateObject(3, 400, 350, 2);
    factoryObj.CreateObject(4, 400, 350, 1);
    vObject = factoryObj.GetObjects();
    for (int i = 0; i < 100; ++i)
        if (i < 30) 
            vObject.push_back(new DynamicObject("ground2", 36 * i, 400, 4));
        else if (i < 60)
            vObject.push_back(new DynamicObject("ground2", 36 * i, 500, 4));
        else
            vObject.push_back(new DynamicObject("ground2", 36 * i - 700, 430, 4));
    vObject.push_back(new DynamicObject("plumbs2", 100, 330, 4));
    vObject.push_back(new DynamicObject("plumbs2", 800, 330, 4));
    vObject.push_back(new DynamicObject("platform7", 1200, 320, 4));
    vObject.push_back(new Mushroom(quadtree, "mushroom1", 1, 300, 100, 2));
    vObject.push_back(new Mushroom(quadtree, "mushroom2", 2, 200, 100, 2));
    for (int i = 0; i < 20; ++i)
    {	
        vObject.push_back(new Coin(600 + 100 * i, 200 + 3 * i, 3));
        vObject.push_back(new Turtle(quadtree, 100 + 10 * i, 100, 2));
    }
    vObject.push_back(new Enemy(quadtree, 500, 100, 2));
    for (vector<GameObject*>::iterator i = vObject.begin(); i != vObject.end(); ++i)
        quadtree->InsertObject(*i);
    mario = new Mario(quadtree, SCREEN_WIDTH, SCREEN_HEIGHT, 400, 200, 2);
    return true;
}

MarioGame::~MarioGame()
{	
    if (mario != 0)
    {	
        delete mario;
    }
    for (vector<GameObject*>::iterator i = vObject.begin(); i != vObject.end(); ++i)
    {	
        if ((*i) != 0)
        {	
            delete (*i);
        }
    }
    if (background != 0)
    {	
        delete background;
    }
    if (quadtree != 0)
    {	
        delete quadtree;
    }
}

void MarioGame::Update(unsigned int gameTime) 
{	
    mario->Update(gameTime);
    return;
}

void MarioGame::Render(unsigned int gameTime)
{	
    if (pGraphic->BeginRender())
    {	
        background->Draw();
        mario->Render(gameTime);
        pGraphic->EndRender();
    }
    return;
}

bool MarioGame::IsGameOver()
{	
    if (pInput->IsKeyPress(DIK_ESCAPE))
        return true;
    return false;
}
